import fs from 'fs'
import path from 'path'

import https from 'https'
import http from 'http'

const DefaultEncoding = 'utf-8'

/**
 * 路径
 */
const RootPath = path.resolve()
const ManifestPath = path.resolve(RootPath, 'src/manifest.json')

export function download(url: string, targetPath: string) {
  try {
    http.get(url, (res) => {
      // file will be stored at this path
      const path = targetPath
      const filePath = fs.createWriteStream(path)
      res.pipe(filePath)
      filePath.on('finish', () => {
        filePath.close()
        console.log('Download Completed', path)
      })
    })
  } catch (error) {
    console.log('Download file exception', error)
  }
}

/**
 * ENV
 */
export function getEnvMode() {
  return process.env.ENV
}

export type EnvObject = Record<string, string>
export function getEnvObject(encoding: BufferEncoding = DefaultEncoding): EnvObject {
  const envFile = getEnvFile(encoding)
  return envFile
    .replace(/\r\n/g, '\n')
    .replace(/\r/g, '\n')
    .split('\n')
    .reduce<EnvObject>((envObject, row) => {
      if (row.trim() !== '') {
        const [key, value] = row.split('=')
        envObject[key] = value
      }
      return envObject
    }, {})
}
export function getEnvPath() {
  const envMode = getEnvMode()
  const envFileName = `.env.${envMode}`
  const filePath = path.resolve(RootPath, envFileName)
  return filePath
}
export function getEnvFile(encoding: BufferEncoding = DefaultEncoding) {
  const envPath = getEnvPath()
  return readTextFile(envPath, encoding)
}
export function saveEnvFile(envObject: EnvObject, encoding: BufferEncoding = DefaultEncoding) {
  const envPath = getEnvPath()
  const data = Object.entries(envObject)
    .map(([key, value]) => `${key}=${value}`)
    .join('\n')
  return saveTextFile(envPath, data)
}

/**
 * Manifest
 */
export function getManifest() {
  return readJSONFile(ManifestPath)
}
export function saveManifest(manifest: object) {
  return saveJSONFile(ManifestPath, manifest)
}

/**
 * IO
 */
export function readJSONFile(filePath: string, encoding: BufferEncoding = DefaultEncoding) {
  const text = readTextFile(filePath, encoding)
  const object = JSON.parse(text)
  return object
}
export function readTextFile(filePath: string, encoding: BufferEncoding = DefaultEncoding) {
  return fs.readFileSync(filePath, { encoding })
}
export function saveJSONFile(filePath: string, data: any, encoding: BufferEncoding = DefaultEncoding) {
  const json = JSON.stringify(data, null, 2)
  return saveTextFile(filePath, json, encoding)
}
export function saveTextFile(filePath: string, data: string, encoding: BufferEncoding = DefaultEncoding) {
  return fs.writeFileSync(filePath, data, encoding)
}
